from datetime import datetime, timedelta
import sys
import os

# 将项目根目录添加到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import app, db
from backend.models.device import Device
from backend.models.script import Script
from backend.models.task import Task

# 使用应用程序上下文连接数据库
with app.app_context():
    # 清空现有数据（可选）
    print("正在清空现有数据...")
    Task.query.delete()
    Script.query.delete()
    Device.query.delete()
    db.session.commit()
    
    # 创建测试设备数据
    print("正在插入设备数据...")
    devices = [
        Device(
            device_id="device_001",
            device_name="测试手机1",
            model="iPhone 13",
            brand="Apple",
            os_version="iOS 16.2",
            status="online",
            ip_address="192.168.1.101",
            port=5555,
            battery_level=85,
            is_usb_connected=True
        ),
        Device(
            device_id="device_002",
            device_name="测试手机2",
            model="Samsung Galaxy S21",
            brand="Samsung",
            os_version="Android 13",
            status="online",
            ip_address="192.168.1.102",
            port=5556,
            battery_level=60,
            is_usb_connected=True
        ),
        Device(
            device_id="device_003",
            device_name="测试平板",
            model="iPad Pro",
            brand="Apple",
            os_version="iPadOS 16.1",
            status="offline",
            ip_address="192.168.1.103",
            port=5557,
            battery_level=45,
            is_usb_connected=False
        ),
        Device(
            device_id="device_004",
            device_name="测试模拟器",
            model="Pixel 6 Pro",
            brand="Google",
            os_version="Android 14",
            status="忙碌",
            ip_address="192.168.1.104",
            port=5558,
            battery_level=90,
            is_usb_connected=False
        )
    ]
    
    # 添加设备到数据库
    for device in devices:
        db.session.add(device)
    db.session.commit()
    
    # 创建测试脚本数据
    print("正在插入脚本数据...")
    scripts = [
        Script(
            name="App启动测试",
            description="测试应用启动时间和稳定性",
            content="""import time\nfrom appium import webdriver\n\n# 配置Appium连接\ndesired_caps = {\n    'platformName': 'Android',\n    'deviceName': 'device',\n    'appPackage': 'com.example.app',\n    'appActivity': 'com.example.app.MainActivity'\n}\n\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n# 记录启动时间\nstart_time = time.time()\n\n# 等待应用完全启动\ndriver.implicitly_wait(10)\n\n# 验证应用是否正常启动\nif driver.find_element_by_id('com.example.app:id/main_text'):\n    end_time = time.time()\n    print(f"应用启动成功，耗时: {end_time - start_time}秒")\nelse:\n    print("应用启动失败")\n\ndriver.quit()""",
            language="python",
            created_by="admin",
            is_public=True,
            version=1
        ),
        Script(
            name="登录功能测试",
            description="测试用户登录功能的正确性",
            content="""import time\nfrom appium import webdriver\n\n# 配置Appium连接\ndesired_caps = {\n    'platformName': 'iOS',\n    'deviceName': 'iPhone',\n    'bundleId': 'com.example.app',\n    'automationName': 'XCUITest'\n}\n\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\n# 输入用户名和密码\ndriver.find_element_by_id('username_field').send_keys('test_user')\ndriver.find_element_by_id('password_field').send_keys('password123')\n\n# 点击登录按钮\ndriver.find_element_by_id('login_button').click()\n\n# 等待登录完成\ntime.sleep(3)\n\n# 验证登录是否成功\ntry:\n    driver.find_element_by_id('welcome_message')\n    print("登录成功")\nexcept:\n    print("登录失败")\n\ndriver.quit()""",
            language="python",
            created_by="admin",
            is_public=True,
            version=1
        ),
        Script(
            name="性能测试",
            description="测试应用在高负载下的性能表现",
            content="""import time\nimport subprocess\n\n# 获取设备信息\ndef get_device_info(device_id):\n    result = subprocess.run(['adb', '-s', device_id, 'shell', 'getprop'], capture_output=True, text=True)\n    return result.stdout\n\n# 监控CPU使用率\ndef monitor_cpu(device_id, duration=30):\n    print(f"监控设备 {device_id} 的CPU使用率，持续 {duration} 秒")\n    start_time = time.time()\n    \n    while time.time() - start_time < duration:\n        result = subprocess.run(['adb', '-s', device_id, 'shell', 'top', '-n', '1'], capture_output=True, text=True)\n        cpu_info = result.stdout\n        print(f"CPU信息: {cpu_info.splitlines()[0]}")\n        time.sleep(5)\n\n# 运行测试\ndef run_test(device_id):\n    print(f"开始在设备 {device_id} 上运行性能测试")\n    # 启动应用\n    subprocess.run(['adb', '-s', device_id, 'shell', 'am', 'start', '-n', 'com.example.app/.MainActivity'])\n    time.sleep(5)\n    \n    # 监控性能\n    monitor_cpu(device_id)\n    \n    # 停止应用\n    subprocess.run(['adb', '-s', device_id, 'shell', 'am', 'force-stop', 'com.example.app'])\n    \n    print("性能测试完成")\n\nif __name__ == '__main__':\n    device_id = 'device_001'  # 替换为实际设备ID\n    run_test(device_id)""",
            language="python",
            created_by="tester",
            is_public=False,
            version=2
        )
    ]
    
    # 添加脚本到数据库
    for script in scripts:
        db.session.add(script)
    db.session.commit()
    
    # 获取刚刚插入的脚本用于任务创建
    script1 = Script.query.filter_by(name="App启动测试").first()
    script2 = Script.query.filter_by(name="登录功能测试").first()
    
    # 获取设备用于任务创建
    device1 = Device.query.filter_by(device_id="device_001").first()
    device2 = Device.query.filter_by(device_id="device_002").first()
    
    # 创建测试任务数据
    print("正在插入任务数据...")
    tasks = [
        Task(
            name="每日自动化测试",
            description="每天运行的应用自动化测试",
            script_id=script1.id,
            status="已完成",
            priority=2,
            start_time=datetime.utcnow() - timedelta(hours=2),
            end_time=datetime.utcnow() - timedelta(hours=1, minutes=30),
            created_by="system"
        ),
        Task(
            name="登录功能验证",
            description="验证登录功能是否正常工作",
            script_id=script2.id,
            status="运行中",
            priority=3,
            start_time=datetime.utcnow() - timedelta(minutes=15),
            created_by="admin"
        ),
        Task(
            name="夜间性能测试",
            description="在夜间进行的性能测试",
            script_id=script1.id,
            status="等待中",
            priority=1,
            start_time=datetime.utcnow() + timedelta(hours=6),
            created_by="tester"
        )
    ]
    
    # 将任务分配给设备
    tasks[0].device = [device1]
    tasks[1].device = [device2]
    
    # 更新设备的当前任务
    device1.current_task_id = tasks[0].id
    device2.current_task_id = tasks[1].id
    
    # 添加任务到数据库
    for task in tasks:
        db.session.add(task)
    db.session.commit()
    
    print("测试数据插入完成！")
    print(f"插入了 {len(devices)} 个设备记录")
    print(f"插入了 {len(scripts)} 个脚本记录")
    print(f"插入了 {len(tasks)} 个任务记录")